require "import"
import "android.app.*"
import "android.os.*"
import "android.widget.*"
import "android.view.*"
import "android.content.*"
import "android.net.*"
import "android.webkit.*"
import "android.content.Intent"
import "android.net.Uri"
import "android.graphics.PorterDuffColorFilter"
import "android.graphics.PorterDuff"
import "android.net.Uri"
import "android.app.*"
import "android.app.ActionBar$TabListener"
import "android.app.AlertDialog"
import "android.app.SearchManager"
import "android.animation.ObjectAnimator"
import "android.animation.ArgbEvaluator"
import "android.animation.ValueAnimator"
import "android.animation.Animator$AnimatorListener"
import "android.content.*"
import "android.content.DialogInterface"
import "android.content.Context"
import "android.content.Intent"
import "android.content.pm.PackageManager"
import "android.content.pm.ApplicationInfo"
import "android.content.res.*"
import "android.content.SharedPreferences"
import "android.graphics.*"
import "android.graphics.Bitmap"
import "android.graphics.Color"
import "android.graphics.drawable.*"
import "android.graphics.drawable.BitmapDrawable"
import "android.graphics.drawable.ColorDrawable"
import "android.graphics.drawable.GradientDrawable"
import "android.graphics.drawable.GradientDrawable"
import "android.graphics.PorterDuff"
import "android.graphics.PorterDuffColorFilter"
import "android.graphics.Typeface"
import "android.graphics.Matrix"
import "android.graphics.Paint"
import "android.graphics.PorterDuffXfermode"
import "android.graphics.RectF"
import "android.graphics.PorterDuff$Mode"
import "android.graphics.Rect"
import "android.graphics.Canvas"
import "android.graphics.BitmapFactory"
import "android.media.MediaPlayer"
import "android.media.MediaMetadataRetriever"
import "android.net.*"
import "android.net.Uri"
import "android.net.TrafficStats"
import "android.os.*"
import "android.os.Build"
import "android.opengl.*"
import "android.provider.MediaStore"
import "android.provider.Settings"
import "android.provider.Settings$Secure"
import "android.telephony.*"
import "android.text.Html"
import "android.text.format.Formatter"
import "android.text.SpannableString"
import "android.text.style.ForegroundColorSpan"
import "android.text.Spannable"
import "android.util.TypedValue"
import "android.util.Config"
import "android.util.DisplayMetrics"
import "android.view.*"
import "android.view.animation.*"
import "android.view.animation.Animation$AnimationListener"
import "android.view.animation.AnimationUtils"
import "android.view.animation.LayoutAnimationController"
import "android.view.inputmethod.InputMethodManager"
import "android.view.View$OnFocusChangeListener"
import "android.view.animation.AccelerateInterpolator"
import "android.view.inputmethod.EditorInfo"
import "android.webkit.MimeTypeMap"
import "android.widget.*"
import "android.widget.ArrayAdapter"
import "android.widget.LinearLayout"
import "android.widget.EditText"
import "android.widget.ListView"
import "android.widget.PullingLayout"
import "android.widget.TextView"
import "android.widget.TimePicker$OnTimeChangedListener"
import "android.widget.PageView$PageTransformer"
import "android.widget.DrawerLayout$DrawerListener"
import "java.io.File"
import "java.io.FileOutputStream"
import "java.io.FileInputStream"
import "java.io.BufferedInputStream"
import "java.net.URLDecoder"
import "java.lang.String"
import "java.util.zip.ZipFile"
import "java.util.regex.Pattern"
import "android.graphics.drawable.ColorDrawable"


--创建一个类
local 中文函数库 = {}


function 重启应用()
    -- By: 一缕清风自在飞
    import "android.content.Intent"
    local intent = activity.getPackageManager().getLaunchIntentForPackage(activity.getPackageName());
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    activity.startActivity(intent)
end

function 搜索(关键词)
    -- By: 寒歌 (QQ: 2113075983)
    if 关键词 then
        import "android.content.Intent"
        import "android.app.SearchManager"
        local intent = Intent()
        intent.setAction(Intent.ACTION_WEB_SEARCH)
        intent.putExtra(SearchManager.QUERY, 关键词)
        activity.startActivity(intent)
    else
        error("传入参数异常")
    end
end

function 图片着色(位图, 颜色)
    -- By: 寒歌 (QQ: 2113075983)
    local bitmap = 位图
    local color = 颜色
    local aa = BitmapDrawable(bitmap)
    aa.setColorFilter(PorterDuffColorFilter(color, PorterDuff.Mode.SRC_ATOP))
    return aa
end

function 保存位图(位图, 路径)
    -- By: 寒歌 (QQ: 2113075983)
    local bm = 位图
    local name = 路径
    if bm then
        import "java.io.FileOutputStream"
        import "java.io.File"
        import "android.graphics.Bitmap"
        name = tostring(name)
        f = File(name)
        out = FileOutputStream(f)
        bm.compress(Bitmap.CompressFormat.PNG, 90, out)
        out.flush()
        out.close()
        return true
    else
        return false
    end
end

function 缩放图片(位图, 缩放级别)
    -- By: 佚名
    local bm = 位图
    local degrees = 缩放级别
    import "android.graphics.Matrix"
    import "android.graphics.Bitmap"
    width = bm.getWidth()
    height = bm.getHeight()
    matrix = Matrix()
    matrix.postRotate(degrees)
    bmResult = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true)
    return bmResult
end

function 匹配汉字(文本)
    -- By: 佚名
    local s = 文本
    local ss = {}
    for k = 1, #s do
        local c = string.byte(s, k)
        if not c then break end
        if (c >= 48 and c <= 57) or (c >= 65 and c <= 90) or (c >= 97 and c <= 122) then
            if not string.char(c):find("%w") then
                table.insert(ss, string.char(c))
            end
        elseif c >= 228 and c <= 233 then
            local c1 = string.byte(s, k + 1)
            local c2 = string.byte(s, k + 2)
            if c1 and c2 then
                local a1, a2, a3, a4 = 128, 191, 128, 191
                if c == 228 then
                    a1 = 184
                elseif c == 233 then
                    a2, a4 = 190, c1 ~= 190 and 191 or 165
                end
                if c1 >= a1 and c1 <= a2 and c2 >= a3 and c2 <= a4 then
                    k = k + 2
                    table.insert(ss, string.char(c, c1, c2))
                end
            end
        end
    end
    return table.concat(ss)
end

function 振动(模式)
    -- By: 烧风 (QQ: 2063597709)
    -- 注: 需要申请控制振动器权限
    -- 振动模式格式: {等待时间,振动时间,等待时间,振动时间,•••,•••,•••,•••••}
    -- 例如: {500,100,500,100,500}
    import "android.content.Context"
    if not 模式 then
        模式 = { 500 }
    end
    vibrator = activity.getSystemService(Context.VIBRATOR_SERVICE)
    vibrator.vibrate(long(模式), -1)
end

--使用方法
--振动({500,100,500,100,500})

function 获取签名(包名)
    -- By: QQ32552732
    return tostring(this.getPackageManager().getPackageInfo(this.getPackageName(),
        ((32552732 / 2 / 2 - 8183) / 10000 - 6 - 231) /
        9).signatures[(32552732 + 0 + 32552732 - (32552732 * 2))].toCharsString())
end

function 提示6(文本内容)
    if 文本内容 ~= nil then
        xxxx = {
            LinearLayout,
            {
                LinearLayout,
                {
                    CardView,
                    radius = '5dp',
                    elevation = '5dp',
                    layout_height = 'wrap_content',
                    layout_margin = '18dp',
                    layout_width = activity.getWidth() / 1.1,
                    CardBackgroundColor = "#FF202124",
                    {
                        TextView,
                        textColor = '#ffffff',
                        layout_marginTop = '15dp',
                        layout_marginBottom = '15dp',
                        layout_margin = '15dp',
                        text = 文本内容,
                    },
                },
            },
        };
        布局 = loadlayout(xxxx)
        local toast = Toast.makeText(activity, "提示", Toast.LENGTH_SHORT).setGravity(Gravity.BOTTOM, 0, 0).setView(布局)
            .show()
    end
end

function 弹窗圆角(控件, 背景色, 上角度, 下角度)
    if not 上角度 then
        上角度 = 25
    end
    if not 下角度 then
        下角度 = 上角度
    end
    控件.setBackgroundDrawable(GradientDrawable()
        .setShape(GradientDrawable.RECTANGLE)
        .setColor(背景色)
        .setCornerRadii({ 上角度, 上角度, 上角度, 上角度, 下角度, 下角度, 下角度, 下角度 }))
end

function MD提示(str, a, b, c, d)
    if time then toasttime = Toast.LENGTH_SHORT else toasttime = Toast.LENGTH_SHORT end
    toasts = {
        CardView,
        id = "toastb",
        CardElevation = c,
        radius = d,
        background = a,
        {
            TextView,
            layout_margin = "7dp",
            textSize = "13sp",
            TextColor = b,
            layout_gravity = "center",
            text = "Hello Ori",
            id = "mess",
        },
    };
    message = tostring(str)
    local toast = Toast.makeText(activity, "内容", toasttime);
    toast.setView(loadlayout(toasts))
    mess.Text = message
    toast.show()
end

function 窗口标题(a)
    activity.setTitle(a)
end

function 载入页面(a)
    activity.setContentView(loadlayout(a))
end

function 窗口全屏()
    activity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN)
end

function 取消全屏()
    activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
end

function 返回桌面()
    activity.moveTaskToBack(true)
end

function 提示(a)
    Toast.makeText(activity, a, Toast.LENGTH_SHORT).show()
end

function 截取(str, str1, str2)
    str1 = str1:gsub("%p", function(s) return ("%" .. s) end)
    return (str:match(str1 .. "(.-)" .. str2))
end

function 替换(str, str1, str2)
    str1 = str1:gsub("%p", function(s) return ("%" .. s) end)
    str2 = str2:gsub("%%", "%%%%")
    return (str:gsub(str1, str2))
end

function 字符串长度(str)
    return (utf8.len(str))
end

function sgg(s, i, j)
    i, j = tonumber(i), tonumber(j)
    i = utf8.offset(s, i)
    j = ((j or -1) == -1 and -1) or utf8.offset(s, j + 1) - 1
    return string.sub(s, i, j)
end

function 状态栏颜色(a)
    if Build.VERSION.SDK_INT >= 21 then
        activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS).setStatusBarColor(a);
    end
end

function 设置文本(a, b)
    a.setText(b)
end

function 关闭页面()
    activity.finish()
end

function 获取文本(a)
    return (a).Text()
end

function 结束程序()
    activity.finish()
end

function 重构页面()
    activity.recreate()
end

function 控件圆角(view, InsideColor, radiu)
    import "android.graphics.drawable.GradientDrawable"
    drawable = GradientDrawable()
    drawable.setShape(GradientDrawable.RECTANGLE)
    drawable.setColor(InsideColor)
    drawable.setCornerRadii({ radiu, radiu, radiu, radiu, radiu, radiu, radiu, radiu });
    view.setBackgroundDrawable(drawable)
end

function 控件背景渐变动画(a, b, c, d, e)
    view = a
    color1 = b
    color2 = c
    color3 = d
    color4 = e
    import "android.animation.ObjectAnimator"
    import "android.animation.ArgbEvaluator"
    import "android.animation.ValueAnimator"
    import "android.graphics.Color"
    colorAnim = ObjectAnimator.ofInt(view, "backgroundColor", { color1, color2, color3, color4 })
    colorAnim.setDuration(3000)
    colorAnim.setEvaluator(ArgbEvaluator())
    colorAnim.setRepeatCount(ValueAnimator.INFINITE)
    colorAnim.setRepeatMode(ValueAnimator.REVERSE)
    colorAnim.start()
end

function 安装判断(a)
    if pcall(function() activity.getPackageManager().getPackageInfo(a, 0) end) then
        return true
    else
        return false
    end
end

function 设置中划线(a)
    import "android.graphics.Paint"
    a.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG)
end

function 设置下划线(a)
    import "android.graphics.Paint"
    a.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG)
end

function 设置字体加粗(a)
    import "android.graphics.Paint"
    a.getPaint().setFakeBoldText(true)
end

function 设置斜体(a)
    import "android.graphics.Paint"
    a.getPaint().setTextSkewX(0.2)
end

function 分享(a)
    text = a
    intent = Intent(Intent.ACTION_SEND);
    intent.setType("text/plain");
    intent.putExtra(Intent.EXTRA_SUBJECT, "分享");
    intent.putExtra(Intent.EXTRA_TEXT, text);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    activity.startActivity(Intent.createChooser(intent, "分享到:"));
end

function 加群(a)
    import "android.net.Uri"
    import "android.content.Intent"
    url = "mqqapi://card/show_pslcard?src_type=internal&version=1&uin=" .. a .. "&card_type=group&source=qrcode"
    activity.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)))
end

function QQ聊天(a)
    import "android.net.Uri"
    import "android.content.Intent"
    url = "mqqwpa://im/chat?chat_type=wpa&uin=" .. a
    activity.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)))
end

function 发送短信(号码, 名称, 内容)
    import "android.net.Uri"
    import "android.content.Intent"
    uri = Uri.parse("smsto:" .. 号码)
    intent = Intent(Intent.ACTION_SENDTO, uri)
    intent.putExtra(名称, 内容)
    intent.setAction("android.intent.action.VIEW")
    activity.startActivity(intent)
end

function 开启WIFI()
    import "android.content.Context"
    wifi = activity.Context.getSystemService(Context.WIFI_SERVICE)
    wifi.setWifiEnabled(true)
end

function 关闭WIFI()
    import "android.content.Context"
    wifi = activity.Context.getSystemService(Context.WIFI_SERVICE)
    wifi.setWifiEnabled(false)
end

function 断开网络()
    import "android.content.Context"
    wifi = activity.Context.getSystemService(Context.WIFI_SERVICE)
    wifi.disconnect()
end

function 创建文件(a)
    import "java.io.File"
    return File(a).createNewFile()
end

function 创建文件夹(a)
    import "java.io.File"
    return File(a).mkdir()
end

function 创建多级文件夹(a)
    import "java.io.File"
    return File(a).mkdirs()
end

function 移动文件(a, b)
    import "java.io.File"
    return File(a).renameTo(File(b))
end

function 写入文件33(a, b)
    return io.open(a, "w"):write(b):close()
end

function 按钮颜色(aa, id)
    aa.getBackground().setColorFilter(PorterDuffColorFilter(id, PorterDuff.Mode.SRC_ATOP))
end

function 编辑框颜色(id, cc)
    id.getBackground().setColorFilter(PorterDuffColorFilter(cc, PorterDuff.Mode.SRC_ATOP));
end

function 进度条颜色(id, cc)
    id.IndeterminateDrawable.setColorFilter(PorterDuffColorFilter(cc, PorterDuff.Mode.SRC_ATOP))
end

function 控件颜色(id, cc)
    id.setBackgroundColor(cc)
end

function 获取手机存储路径()
    return Environment.getExternalStorageDirectory().toString()
end

function 获取屏幕宽()
    return activity.getWidth()
end

function 获取屏幕高()
    return activity.getHeight()
end

function 文件是否存在(id)
    return File(id).exists()
end

function 关闭侧滑()
    drawerLayout.closeDrawer(3)
end

function 打开侧滑()
    drawerLayout.openDrawer(3)
end

function 显示(id)
    id.setVisibility(0)
end

function 隐藏(id)
    id.setVisibility(8)
end

function 播放本地音乐(id)
    import "android.content.Intent"
    import "android.net.Uri"
    intent = Intent(Intent.ACTION_VIEW)
    uri = Uri.parse("file://" .. id)
    intent.setDataAndType(uri, "audio/mp3")
    this.startActivity(intent)
end

function 在线播放音乐(id)
    import "android.content.Intent"
    import "android.net.Uri"
    intent = Intent(Intent.ACTION_VIEW)
    uri = Uri.parse(id)
    intent.setDataAndType(uri, "audio/mp3")
    this.startActivity(intent)
end

function 播放本地视频(id)
    import "android.content.Intent"
    import "android.net.Uri"
    intent = Intent(Intent.ACTION_VIEW)
    uri = Uri.parse("file://" .. id)
    intent.setDataAndType(uri, "video/mp4")
    activity.startActivity(intent)
end

function 在线播放视频(id)
    import "android.content.Intent"
    import "android.net.Uri"
    intent = Intent(Intent.ACTION_VIEW)
    uri = Uri.parse(id)
    intent.setDataAndType(uri, "video/mp4")
    activity.startActivity(intent)
end

function 打开app(id)
    packageName = id
    import "android.content.Intent"
    import "android.content.pm.PackageManager"
    manager = activity.getPackageManager()
    open = manager.getLaunchIntentForPackage(packageName)
    this.startActivity(open)
end

function 卸载app(id)
    import "android.net.Uri"
    import "android.content.Intent"
    包名 = id
    uri = Uri.parse("package:" .. 包名)
    intent = Intent(Intent.ACTION_DELETE, uri)
    activity.startActivity(intent)
end

function 安装app(id)
    import "android.content.Intent"
    import "android.net.Uri"
    intent = Intent(Intent.ACTION_VIEW)
    安装包路径 = id
    intent.setDataAndType(Uri.parse("file://" .. 安装包路径), "application/vnd.android.package-archive")
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
    activity.startActivity(intent)
end

function 系统下载文件(a, b, c)
    import "android.content.Context"
    import "android.net.Uri"
    downloadManager = activity.getSystemService(Context.DOWNLOAD_SERVICE);
    url = Uri.parse(a);
    request = DownloadManager.Request(url);
    request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE|DownloadManager.Request.NETWORK_WIFI);
    request.setDestinationInExternalPublicDir(b, c);
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    downloadManager.enqueue(request);
end

function 弹窗1(a, b, c, functions)
    dialog = AlertDialog.Builder(this)
        .setTitle(a)
        .setMessage(b)
        .setPositiveButton(c, {
            onClick = function(v)
                functions()
            end
        })
        .show()
    dialog.create()
end

function 波纹(id, ys)
    import "android.content.res.ColorStateList"
    local attrsArray = { android.R.attr.selectableItemBackgroundBorderless }
    local typedArray = activity.obtainStyledAttributes(attrsArray)
    ripple = typedArray.getResourceId(0, 0)
    aoos = activity.Resources.getDrawable(ripple)
    aoos.setColor(ColorStateList(int[0].class { int {} }, int { ys }))
    id.setBackground(aoos.setColor(ColorStateList(int[0].class { int {} }, int { ys })))
end

function 随机数(a, b)
    return math.random(a, b)
end

function 删除控件(a, b)
    return (a).removeView(b)
end

function 状态栏亮色()
    if Build.VERSION.SDK_INT >= 23 then
        activity.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
    end
end

function 导入包类(a)
    return import(a)
end

--点击事件
function 点击事件(a, ok)
    a.onClick = ok
end

--长按事件
function 长按事件(a, ok)
    a.onLongClick = ok
end

--列表项目被单击
function 列表项目被单击(a, ok)
    a.onItemClick = ok
end

--列表项目被长按
function 列表项目被长按(a, ok)
    a.onItemLongClick = ok
end

--控件可视
function 控件可视(id)
    id.setVisibility(0)
end

--控件不可视
function 控件不可视(id)
    id.setVisibility(8)
end

--关闭侧滑
function 关闭侧滑(ch)
    ch.closeDrawer(3)
end

--打开侧滑
function 打开侧滑(ch)
    ch.openDrawer(3)
end

--关闭右侧滑
function 关闭右侧滑(ch)
    ch.closeDrawer(5)
end

--打开右侧滑
function 打开右侧滑(ch)
    ch.openDrawer(5)
end

--关闭左侧滑
function 关闭左侧滑(ch)
    ch.closeDrawer(3)
end

--打开左侧滑
function 打开左侧滑(ch)
    ch.openDrawer(3)
end

--设置主题
function 设置主题(theme)
    activity.setTheme(theme)
end

--设置标题栏标题
function 设置标题(标题)
    activity.setTitle(标题)
end

--隐藏标题栏
function 隐藏标题栏()
    activity.ActionBar.hide()
end

--设置布局
function 设置布局(a)
    activity.setContentView(loadlayout(a))
end

--布局内插入布局
function 布局内插入布局(控件, 布局)
    控件.addView(loadlayout(布局))
end

--使弹出的输入法不影响布局
function 使弹出的输入法不影响布局()
    activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)
end

function 取消标题栏阴影()
    activity.ActionBar.setElevation(0)
end

function 编辑框光标颜色修改函数(id, Color)
    import 'android.graphics.Color'
    import 'android.graphics.PorterDuff'
    import 'android.graphics.PorterDuffColorFilter'
    local mEditorField = TextView.getDeclaredField('mEditor')
    mEditorField.setAccessible(true)
    local mEditor = mEditorField.get(id)
    local field = Editor.getDeclaredField('mCursorDrawable')
    field.setAccessible(true)
    local mCursorDrawable = field.get(mEditor)
    local mccdf = TextView.getDeclaredField('mCursorDrawableRes')
    mccdf.setAccessible(true)
    local mccd = activity.getResources().getDrawable(mccdf.getInt(id))
    mccd.setColorFilter(PorterDuffColorFilter(Color, PorterDuff.Mode.SRC_ATOP))
    mCursorDrawable[0] = mccd
    mCursorDrawable[1] = mccd
end

--使弹出的输入法影响布局
function 使弹出的输入法影响布局()
    activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
end

--重置当前页面
function 重置当前页面()
    activity.recreate()
end

--状态栏暗色
function 状态栏暗色()
    if Build.VERSION.SDK_INT >= 23 then
        --activity.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        activity.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)
    end
end

--隐藏状态栏
function 隐藏状态栏()
    activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
end

--导航栏颜色
function 导航栏颜色(a)
    if Build.VERSION.SDK_INT >= 21 then
        activity.getWindow().setNavigationBarColor(a);
    else
    end
end

--通知栏颜色
function 通知栏颜色(id)
    if Build.VERSION.SDK_INT >= 21 then
        activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS).setStatusBarColor(id);
    end
end

--仿FusionApp函数---------------------------------------------------
--进入子页面
function 进入子页面(页面, 参数)
    if 参数 == nil then
        activity.newActivity(页面)
    elseif 参数["链接"] == nil then
        activity.newActivity(页面)
    elseif 参数["标题"] == nil then
        链接 = 参数["链接"]
        标题 = 参数["标题"]
        activity.newActivity(页面, { 链接, 标题 })
    else
        链接 = 参数["链接"]
        标题 = 参数["标题"]
        activity.newActivity(页面, { 链接, 标题 })
    end
end

--intent类操作(已整理)--20191222-----------------------------------------------------------------------------------
--1.调用系统发送短信
function 调用系统发送短信(内容1, 号码1)
    uri = Uri.parse("smsto:" .. 号码1)
    intent = Intent(Intent.ACTION_SENDTO, uri)
    intent.putExtra("sms_body", 内容1)
    intent.setAction("android.intent.action.VIEW")
    activity.startActivity(intent)
end

--2.加QQ群
function 加QQ群(群号)
    url = "mqqapi://card/show_pslcard?src_type=internal&version=1&uin=" .. 群号 .. "&card_type=group&source=qrcode"
    activity.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)))
end

--3.联系QQ
function 联系QQ(QQ号码)
    url = "mqqwpa://im/chat?chat_type=wpa&uin=" .. QQ号码
    activity.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)))
end

--4.分享文件
function 分享文件(文件路径)
    FileName = tostring(File(文件路径).Name)
    ExtensionName = FileName:match("%.(.+)")
    Mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(ExtensionName)
    intent = Intent();
    intent.setAction(Intent.ACTION_SEND);
    intent.setType(Mime);
    file = File(文件路径);
    uri = Uri.fromFile(file);
    intent.putExtra(Intent.EXTRA_STREAM, uri);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    activity.startActivity(Intent.createChooser(intent, "分享到:"));
end

--5.分享文本


--6.调用系统浏览器搜索
function 调用系统浏览器搜索(搜索内容)
    intent = Intent()
    intent.setAction(Intent.ACTION_WEB_SEARCH)
    intent.putExtra(SearchManager.QUERY, 搜索内容)
    activity.startActivity(intent)
end

--7.调用系统浏览器打开链接
function 调用系统浏览器打开链接(网页链接)
    viewIntent = Intent("android.intent.action.VIEW", Uri.parse(网页链接))
    activity.startActivity(viewIntent)
end

--8.打开程序
function 打开程序(程序包名)
    manager = activity.getPackageManager()
    open = manager.getLaunchIntentForPackage(程序包名)
    activity.startActivity(open)
end

--9.安装程序
function 安装程序(安装包路径)
    intent = Intent(Intent.ACTION_VIEW)
    intent.setDataAndType(Uri.parse("file://" .. 安装包路径), "application/vnd.android.package-archive")
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
    activity.startActivity(intent)
end

--10.卸载程序
function 卸载程序(包名)
    uri = Uri.parse("package:" .. 包名)
    intent = Intent(Intent.ACTION_DELETE, uri)
    activity.startActivity(intent)
end

--11.播放MP4
function 播放MP4(视频路径)
    intent = Intent(Intent.ACTION_VIEW)
    uri = Uri.parse("file://" .. 视频路径)
    intent.setDataAndType(uri, "video/mp4")
    activity.startActivity(intent)
end

--12.播放MP3
function 播放MP3(音乐路径)
    intent = Intent(Intent.ACTION_VIEW)
    uri = Uri.parse("file://" .. 音乐路径)
    intent.setDataAndType(uri, "audio/mp3")
    this.startActivity(intent)
end

--13.拨号
function 拨号(电话号码)
    uri = Uri.parse("tel:" .. 电话号码);
    intent = Intent(Intent.ACTION_CALL, uri);
    intent.setAction("android.intent.action.VIEW");
    activity.startActivity(intent);
end

--14.搜索应用
function 搜索应用(包名)
    intent = Intent("android.intent.action.VIEW")
    intent.setData(Uri.parse("market://details?id=" .. 包名))
    activity.startActivity(intent)
end

--14.调用系统打开文件
function 调用系统打开文件(path)
    FileName = tostring(File(path).Name)
    ExtensionName = FileName:match("%.(.+)")
    Mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(ExtensionName)
    if Mime then
        intent = Intent()
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(File(path)), Mime);
        activity.startActivity(intent)
        return true
    else
        return false
    end
end

--16.发送彩信
function 发送彩信(图片路径, 邮件地址, 邮件内容, 类型)
    uri = Uri.parse("file://" .. 图片路径) --图片路径
    intent = Intent();
    intent.setAction(Intent.ACTION_SEND);
    intent.putExtra("address", 邮件地址) --邮件地址
    intent.putExtra("sms_body", 邮件内容) --邮件内容
    intent.putExtra(Intent.EXTRA_STREAM, uri)
    intent.setType(类型) --设置类型
    activity.startActivity(intent)
end

--17.调用系统设置
--ACTION_SETTINGS	系统设置
function 打开系统设置()
    local intent = Intent(Settings.ACTION_SETTINGS);
    activity.startActivity(intent);
end

--ACTION_APN_SETTINGS APN设置
function 打开APN设置()
    local intent = Intent(Settings.ACTION_APN_SETTINGS);
    activity.startActivity(intent);
end

--ACTION_LOCATION_SOURCE_SETTINGS 位置和访问信息
function 打开位置和访问信息设置()
    local intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
    activity.startActivity(intent);
end

--ACTION_WIRELESS_SETTINGS 网络设置
function 打开网络设置()
    local intent = Intent(Settings.ACTION_WIRELESS_SETTINGS);
    activity.startActivity(intent);
end

--ACTION_AIRPLANE_MODE_SETTINGS 无线和网络热点设置
function 打开无线和网络热点设置()
    local intent = Intent(Settings.ACTION_AIRPLANE_MODE_SETTINGS);
    activity.startActivity(intent);
end

--ACTION_SECURITY_SETTINGS 位置和安全设置
function 打开位置和安全设置()
    local intent = Intent(Settings.ACTION_SECURITY_SETTINGS);
    activity.startActivity(intent);
end

--ACTION_WIFI_SETTINGS 无线网WIFI设置
function 打开无线网WIFI设置()
    local intent = Intent(Settings.ACTION_WIFI_SETTINGS);
    activity.startActivity(intent);
end

--ACTION_WIFI_IP_SETTINGS 无线网IP设置
function 打开无线网IP设置()
    local intent = Intent(Settings.ACTION_WIFI_IP_SETTINGS);
    activity.startActivity(intent);
end

--ACTION_BLUETOOTH_SETTINGS 蓝牙设置
function 打开蓝牙设置()
    local intent = Intent(Settings.ACTION_BLUETOOTH_SETTINGS);
    activity.startActivity(intent);
end

--ACTION_DATE_SETTINGS 时间和日期设置
function 打开时间和日期设置()
    local intent = Intent(Settings.ACTION_DATE_SETTINGS);
    activity.startActivity(intent);
end

--ACTION_SOUND_SETTINGS 声音设置
function 打开声音设置()
    local intent = Intent(Settings.ACTION_SOUND_SETTINGS);
    activity.startActivity(intent);
end

--ACTION_DISPLAY_SETTINGS 显示设置——字体大小等
function 打开显示设置()
    local intent = Intent(Settings.ACTION_DISPLAY_SETTINGS);
    activity.startActivity(intent);
end

--ACTION_LOCALE_SETTINGS 语言设置
function 打开语言设置()
    local intent = Intent(Settings.ACTION_LOCALE_SETTINGS);
    activity.startActivity(intent);
end

--ACTION_INPUT_METHOD_SETTINGS 输入法设置
function 打开输入法设置()
    local intent = Intent(Settings.ACTION_INPUT_METHOD_SETTINGS);
    activity.startActivity(intent);
end

--ACTION_USER_DICTIONARY_SETTINGS 用户词典
function 打开用户词典()
    local intent = Intent(Settings.ACTION_USER_DICTIONARY_SETTINGS);
    activity.startActivity(intent);
end

--ACTION_APPLICATION_SETTINGS 应用程序设置
function 打开应用程序设置()
    local intent = Intent(Settings.ACTION_APPLICATION_SETTINGS);
    activity.startActivity(intent);
end

--ACTION_APPLICATION_DEVELOPMENT_SETTINGS 应用程序设置 开发设置
function 打开开发者选项()
    local intent = Intent(Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS);
    activity.startActivity(intent);
end

--ACTION_QUICK_LAUNCH_SETTINGS 快速启动设置
function 打开快速启动设置()
    local intent = Intent(Settings.ACTION_QUICK_LAUNCH_SETTINGS);
    activity.startActivity(intent);
end

--ACTION_MANAGE_APPLICATIONS_SETTINGS 已下载（安装）软件列表
function 打开已下载软件列表()
    local intent = Intent(Settings.ACTION_MANAGE_APPLICATIONS_SETTINGS);
    activity.startActivity(intent);
end

--ACTION_SYNC_SETTINGS 应用程序数据同步设置
function 打开应用程序数据同步设置()
    local intent = Intent(Settings.ACTION_SYNC_SETTINGS);
    activity.startActivity(intent);
end

--ACTION_NETWORK_OPERATOR_SETTINGS 可用网络搜索
function 打开可用网络搜索()
    local intent = Intent(Settings.ACTION_NETWORK_OPERATOR_SETTINGS);
    activity.startActivity(intent);
end

--ACTION_DATA_ROAMING_SETTINGS 移动网络设置
function 打开移动网络设置()
    local intent = Intent(Settings.ACTION_DATA_ROAMING_SETTINGS);
    activity.startActivity(intent);
end

--ACTION_INTERNAL_STORAGE_SETTINGS 默认存储设置
function 打开默认存储设置()
    local intent = Intent(Settings.ACTION_INTERNAL_STORAGE_SETTINGS);
    activity.startActivity(intent);
end

--ACTION_MEMORY_CARD_SETTINGS 默认存储设置
function 打开SD卡存储设置()
    local intent = Intent(Settings.ACTION_MEMORY_CARD_SETTINGS);
    activity.startActivity(intent);
end

function 支付宝扫一扫()
    import "android.net.Uri"
    import "android.content.Intent"
    intent = Intent(Intent.ACTION_VIEW, Uri.parse("alipayqr://platformapi/startapp?saId=10000007"))
    activity.startActivity(intent)
end

--调用方法
--支付宝扫一扫()



function 微信扫一扫()
    import "android.content.Intent"
    import "android.content.ComponentName"
    intent = Intent()
    intent.setComponent(ComponentName("com.tencent.mm", "com.tencent.mm.ui.LauncherUI"))
    intent.putExtra("LauncherUI.From.Scaner.Shortcut", true)
    intent.setFlags(335544320)
    intent.setAction("android.intent.action.VIEW")
    activity.startActivity(intent)
end

--调用方法
--微信扫一扫()


--Luago中文函数


function 运行代码(代码)
    pcall(function()
        load(代码)()
    end)
end

function 页内查找(词)
    webView.findAllAsync(词) --页内查找
    --webView.findNext(false)--查找后的上翻功能，上一个关键词
    --webView.findNext(true)--查找后的下翻功能，下一个关键词
end

function 网页源码()
    webView.loadUrl("view-source:" .. webView.url)
end

function 网页前进()
    webView.goForward() --网页前进
end

function 网页后退()
    webView.goBack() --网页返回
end

function 弹出消息(a)
    Toast.makeText(activity, a, Toast.LENGTH_SHORT).show()
end

function 分享链接()
    分享文本(webView.getUrl())
end

function 退出页面()
    activity.finish()
end

function 退出程序()
    os.exit()
end

function 复制链接()
    import "android.content.*"
    activity.getSystemService(Context.CLIPBOARD_SERVICE).setText(webView.getUrl())
    提示("链接复制成功")
end

function 停止加载()
    webView.stopLoading() --停止加载网页
end

function 刷新网页()
    webView.loadUrl(webView.getUrl()) --刷新网页
end

function QQ(h)
    url = "mqqapi://card/show_pslcard?src_type=internal&source=sharecard&version=1&uin=" .. h
    activity.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)))
end

function 加载Js(js)
    if js == nil then
    else
        webView.loadUrl("javascript:" .. "(function() {" .. js .. "})()")
    end
end

function 屏蔽元素(table)
    for i, V in pairs(table) do
        加载Js(webView, [[document.getElementsByClassName(']] .. V .. [[')[0].style.display='none';]])
    end
end

function 加载js(js)
    --状态监听
    webView.setWebViewClient {
        shouldOverrideUrlLoading = function(view, url)
            --Url即将跳转
        end,
        onPageStarted = function(view, url, favicon)
            --网页加载
        end,
        onPageFinished = function(view, url)
            --网页加载完成
            webView.loadUrl(
                'javascript:var hm=document.createElement("script");hm.src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js";var s=document.getElementsByTagName("title")[0]; s.parentNode.insertBefore(hm,s);' ..
                "(function() {" .. js .. "})()")
        end
    }
end --不是每个网页都加载了这个jQuery库

function 网页源码2()
    --请复制到fa里面测试，否则会报错
    加载Js([[s=document.documentElement.outerHTML;document.write('<body></body>');document.body.innerText=s;]])
end

function 加载网页(url)
    webView.loadUrl(url)
end

function 复制文本(str)
    import "android.content.*"
    activity.getSystemService(Context.CLIPBOARD_SERVICE).setText(str)
    提示("已复制")
end

function 加载网页2(id, url)
    id.loadUrl(url)
end

function 下载文件(直链, 名称)
    import "android.content.Context"
    import "android.net.Uri"
    downloadManager = activity.getSystemService(Context.DOWNLOAD_SERVICE)
    request = DownloadManager.Request(Uri.parse(直链))
    request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE|DownloadManager.Request.NETWORK_WIFI)
    request.setDestinationInExternalPublicDir("Download", 名称)
    --request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)--是否通知栏显示
    downloadManager.enqueue(request)
end

function 设置浏览器下载监听2()
    webView.setDownloadListener { --文件下载监听
        onDownloadStart = function(链接, UA, 处理, 类型, 大小)
            surl = Uri.parse(链接)
            down_url = surl.authority .. surl.path
            下载dia = AlertDialog.Builder(this)
                .setTitle("要下载文件吗？")
                .setMessage("链接：" .. down_url .. "\n\n大小：" .. string.format("%.2f", 大小 / 1048576) .. "MB")
                .setPositiveButton("下载文件", function()
                    下载文件(链接)
                    print("请在通知栏查看下载进度")
                end)
                .setNeutralButton("取消", nil)
            下载diashow = 下载dia.show()
            dialogWindow = 下载diashow.getWindow();
            dialogWindow.setGravity(Gravity.BOTTOM);
            --设置弹窗宽度
            p = dialogWindow.getAttributes();
            p.width = activity.width;
            --p.height=activity.height/2;
            dialogWindow.setAttributes(p);
        end }
end

function 打开外部应用2()
    webView.setWebViewClient {
        --如果改成MyWebView使用此段设置会报错
        shouldOverrideUrlLoading = function(view, url)
            if not url:find "http" and not url:find "ftp" then --此段用于打开外部应用，在url里没有找到这两项，则视为外部链接
                surl = Uri.parse(url)
                url_scheme = surl.scheme
                对话框() --提示打开
                    .设置标题("要打开外部应用吗？")
                    .设置消息("Scheme：" .. url_scheme)
                    .设置积极按钮("打开", function()
                        pcall(function() --此处使用pcall以免因为用户没有安装应用而报错
                            intent = Intent(Intent.ACTION_VIEW, Uri.parse(url));
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                            this.startActivity(intent); --跳转到指定的应用。如果很久都没有跳转检查是否安装或禁用自启或性能低的设备调起时间长一点
                        end)
                    end)
                    .设置消极按钮("留在此页")
                    .显示()
                pweb.stopLoading() --停止加载以免显示加载错误的页面
            end
            if url == "about:blank" then
                ptitle.text = "无网页加载"
                --pweb.loadUrl("https://picabstract-preview-ftn.weiyun.com/ftn_pic_abs_v3/b48956009f9a3057173eb535043ac6dc8bd5ebea21ba59b072f5d9046af41d3d8254bc03610ccd1ca11287a14d14a346?pictype=scale&from=30113&version=3.3.3.3&uin=2572560133&fname=atm.png&size=750")
            end
        end }
end

function 页内查找2()
    ILayout = {

        LinearLayout,
        orientation = "vertical",
        Focusable = true,
        backgroundColor = "#00000000",
        FocusableInTouchMode = true,
        layout_width = 'fill', --布局宽度
        {
            LinearLayout,
            orientation = "horizontal", --横排列
            layout_width = "fill",
            orientation = "horizontal",
            layout_height = "44dp",

            {

                LinearLayout,
                layout_height = "fill",
                layout_weight = "1",
                orientation = "horizontal",
                {
                    EditText,
                    layout_gravity = "center",
                    textSize = "16sp",
                    layout_weight = "1",
                    layout_marginRight = "10dp",
                    id = "页内查找EditText",
                    hint = "要查找的内容",
                    singleLine = true,

                },
            },
        },
        {
            TextView,
            text = "待查找",
            layout_gravity = "center",
            gravity = "center",
            id = "查找提示区",
        },
        {
            Button,
            layout_width = "fill",
            layout_marginTop = "5dp",
            layout_height = "1dp",
            layout_gravity = "center_horizontal",
            backgroundColor = "#FFDCDCDC",
            style = "?android:attr/borderlessButtonStyle",
        },
        {
            LinearLayout,
            layout_width = "fill",
            orientation = "horizontal",
            backgroundColor = "#2B000000",
            layout_height = "44dp",
            {
                LinearLayout,
                gravity = "center",
                layout_weight = "1",
                layout_height = "44dp",
                BackgroundColor = "#FFFAFAFA",
                {
                    TextView,
                    text = "上翻",
                    textColor = "#333333",
                    layout_gravity = "center",
                    gravity = "center",
                    textSize = "14sp",
                    layout_width = "fill",  --布局宽度
                    layout_height = "fill", --布局高度
                    id = "上翻",
                    onClick = function() webView.findNext(false) end,
                },
            },
            {
                Button,
                layout_width = "1dp",
                layout_height = "fill",
                layout_gravity = "center_horizontal",
                backgroundColor = "#FFDCDCDC",
                style = "?android:attr/borderlessButtonStyle",
            },
            {
                LinearLayout,
                gravity = "center",
                layout_weight = "1",
                layout_height = "44dp",
                BackgroundColor = "#FFFAFAFA",
                {
                    TextView,
                    text = "下翻",
                    textColor = "#333333",
                    layout_gravity = "center",
                    gravity = "center",
                    layout_width = "fill",  --布局宽度
                    layout_height = "fill", --布局高度
                    id = "下翻",
                    textSize = "14sp",
                    onClick = function() webView.findNext(true) end,
                },
            },
            {
                Button,
                layout_width = "1dp",
                layout_height = "fill",
                layout_gravity = "center_horizontal",
                backgroundColor = "#FFDCDCDC",
                style = "?android:attr/borderlessButtonStyle",
            },
            {
                LinearLayout,
                gravity = "center",
                layout_weight = "1",
                layout_height = "44dp",
                BackgroundColor = "#FFFAFAFA",
                {
                    TextView,
                    text = "关闭",
                    textColor = "#333333",
                    layout_gravity = "center",
                    gravity = "center",
                    textSize = "14sp",
                    layout_width = "fill",  --布局宽度
                    layout_height = "fill", --布局高度
                    id = "关闭",
                    onClick = function()
                        webView.findAllAsync("nill")
                    end
                },

            },

        },

    };


    AlertDialog.Builder(this)
        .setTitle("页内查找") --对话框标题
        .setView(loadlayout(ILayout)) --自定义布局
        .show()


    页内查找EditText.addTextChangedListener {
        onTextChanged = function(s)
            webView.findAllAsync(页内查找EditText.text)
        end }

    webView.setFindListener {
        onFindResultReceived = function(position, all, b)
            查找提示区.setText("当前第" .. (position + 1) .. "个结果，" .. "总共找到" .. all .. "个");
        end }
end

function 无图模式()
    webView.getSettings().setLoadsImagesAutomatically(false)
end

function 上帝模式()
    加载Js([[var timeOutEvent=0;

window.ontouchstart=function(e) {

timeOutEvent=setTimeout(function(){

timeOutEvent=0;

var v=e.path[0];

var name="";

if (v.id!=""){

var name="(#"+v.id+")";

}else if(v.className!=""){

var name="(."+v.className+")";
};
var r=confirm("确定删除?"+name);
if (r==true){
 v.remove();
  };
 },500);
};
window.ontouchend=function() {
clearTimeout(timeOutEvent);
if (timeOutEvent != 0) {
}
};
window.ontouchmove=function() {
clearTimeout(timeOutEvent);
timeOutEvent = 0;
};]])
end

function 分享文本(str)
    import "android.content.Intent"
    intent = Intent(Intent.ACTION_SEND);
    intent.setType("text/plain");
    intent.putExtra(Intent.EXTRA_TEXT, str);
    activity.startActivityForResult(intent, 0)
end

--VPN状态监测
function isVpnUsed()
    import "java.net.NetworkInterface"
    import "java.util.Collections"
    import "java.util.Enumeration"
    import "java.util.Iterator"
    local nlp = NetworkInterface.getNetworkInterfaces();
    if (nlp ~= nil) then
        local it = Collections.list(nlp).iterator();
        while (it.hasNext()) do
            local nlo = it.next();
            if (nlo.isUp() and nlo.getInterfaceAddresses().size() ~= 0) then
                if ((tostring(nlo):find("tun0")) or (tostring(nlo):find("ppp0"))) then
                    return true
                end
            end
        end
        return false
    end
end

function 使用ADM下载()
    webView.setDownloadListener(DownloadListener {
        onDownloadStart = function(url, userAgent, contentDisposition, mimetype, contentLength, Filename)
            file_name = tostring(Uri.parse(String(url)).getLastPathSegment())
            local dialog = AlertDialog.Builder(activity)
                .setTitle("是否下载" .. file_name .. "？")
                .setMessage("下载链接:" .. url)
                .setPositiveButton("下载", {
                    onClick = function()
                        downloadManager = activity.getSystemService(Context.DOWNLOAD_SERVICE);
                        url = Uri.parse(url)
                        request = DownloadManager.Request(url);
                        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE|
                            DownloadManager.Request.NETWORK_WIFI)
                        request.setDestinationInExternalPublicDir("Download", file_name)
                        request.setTitle(file_name)
                        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                        downloadManager.enqueue(request)
                    end
                })
                .setNegativeButton("取消", nil)
            if installed("com.dv.adm.pay") then
                dialog.setNeutralButton("使用ADM下载", {
                    onClick = function()
                        this.startActivity(
                            Intent().setAction(Intent.ACTION_SEND).setType("text/*").putExtra(Intent.EXTRA_TEXT, url)
                            .setClassName(
                                "com.dv.adm.pay", "com.dv.adm.pay.AEditor")
                        )
                    end
                })
            end
            dialog.show()
        end })
end

function 保存网页图片()
    webView.setOnLongClickListener(View.OnLongClickListener {
        onLongClick = function(v)
            result = v.getHitTestResult()
            mtype = result.getType()
            if mtype == WebView.HitTestResult.IMAGE_TYPE then
                url = result.getExtra()
                AlertDialog.Builder(activity)
                    .setTitle("提示")
                    .setMessage("是否保存该图片？")
                    .setPositiveButton("确定", {
                        onClick = function()
                            downloadManager = activity.getSystemService(Context.DOWNLOAD_SERVICE)
                            url = Uri.parse(url)
                            file_name = "picture_" .. os.time()
                            request = DownloadManager.Request(url);
                            request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE|
                                DownloadManager.Request.NETWORK_WIFI)
                            request.setDestinationInExternalPublicDir("Download", file_name)
                            request.setTitle(file_name)
                            request.setNotificationVisibility(DownloadManager.Request
                                .VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                            downloadManager.enqueue(request)
                        end
                    })
                    .show()
            end
        end })
end

--屏幕旋转模式
function 自动旋转()
    activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
end

function 横屏模式()
    activity.setRequestedOrientation(0);
end

function 竖屏模式()
    activity.setRequestedOrientation(1);
end

function 获取悬浮窗权限()
    intent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
    intent.setData(Uri.parse("package:" .. activity.getPackageName()));
    activity.startActivityForResult(intent, 100);
end

function 进入页面(na)
    activity.newActivity(na)
end

function 进入首页()
    activity.newActivity("main")
end

function 转换字符串(zfc)
    tostring(zfc)
end

function 保存文本(nam, text)
    activity.setSharedData(nam, text)
end

function 读取文本(nam)
    activity.getSharedData(nam)
end

function 随机数(最小值, 最大值)
    math.random(最小值, 最大值)
end

function 循环(cs, cr)
    for i = cs, cr do
        循环事件()
    end
end

function wifi状态()
    connManager = activity.getSystemService(Context.CONNECTIVITY_SERVICE)
    mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    if tostring(mWifi):find("none)") then
        wifi未连接事件()
    else
        wifi连接事件()
    end
end

function 数据网络状态()
    manager = activity.getSystemService(Context.CONNECTIVITY_SERVICE);
    gprs = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
    if tostring(gprs) == "CONNECTED" then
        数据网络连接事件()
    end
end

function 打开wifi()
    import "android.content.Context"
    wifi = activity.Context.getSystemService(Context.WIFI_SERVICE)
    wifi.setWifiEnabled(true) --关闭则false
end

function 关闭wifi()
    import "android.content.Context"
    wifi = activity.Context.getSystemService(Context.WIFI_SERVICE)
    wifi.setWifiEnabled(false) --关闭则false
end

function 打开应用(程序包名)
    packageName = 应用包名
    import "android.content.Intent"
    import "android.content.pm.PackageManager"
    manager = activity.getPackageManager()
    open = manager.getLaunchIntentForPackage(packageName)
    this.startActivity(open)
end

function 系统设置(名称)
    import "android.content.Intent"
    import "android.provider.Settings"
    intent = Intent(名称)
    this.startActivity(intent)
end

function 分享文字(text)
    intent = Intent(Intent.ACTION_SEND);
    intent.setType("text/plain");
    intent.putExtra(Intent.EXTRA_SUBJECT, "分享");
    intent.putExtra(Intent.EXTRA_TEXT, text);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    activity.startActivity(Intent.createChooser(intent, "分享到:"));
end

function 水印分享(text, 程序名称)
    intent = Intent(Intent.ACTION_SEND);
    intent.setType("text/plain");
    intent.putExtra(Intent.EXTRA_SUBJECT, "分享");
    intent.putExtra(Intent.EXTRA_TEXT, text .. "-来自" .. 程序名称 .. "客户端");
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    activity.startActivity(Intent.createChooser(intent, "分享到:"));
end

function 加入群聊(群聊号)
    import "android.net.Uri"
    import "android.content.Intent"
    --加群
    url = "mqqapi://card/show_pslcard?src_type=internal&version=1&uin=" .. 群聊号 .. "&card_type=group&source=qrcode"
    activity.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)))
end

function 加入QQ(QQ号)
    url = "mqqwpa://im/chat?chat_type=wpa&uin=" .. QQ号
    activity.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)))
end

function 申请root()
    os.execute("su")
end

function 水珠动画(控件, 时间)
    import "android.animation.ObjectAnimator"
    ObjectAnimator().ofFloat(控件, "scaleX", { 1, .8, 1.3, .9, 1 }).setDuration(时间).start()
    ObjectAnimator().ofFloat(控件, "scaleY", { 1, .8, 1.3, .9, 1 }).setDuration(时间).start()
end

function 删除文件(路径)
    os.execute("su -c rm -r " .. 路径)
end

function 文本颜色(id, 颜色)
    id.setTextColor(颜色)
end

function 图片着色(id, 颜色)
    id.setColorFilter(颜色)
end

function 图片旋转(id, 时间)
    view = id
    import 'android.view.animation.Animation'
    import 'android.view.animation.RotateAnimation'
    rotate = RotateAnimation(0, 360,
        Animation.RELATIVE_TO_SELF, 0.5,
        Animation.RELATIVE_TO_SELF, 0.5)
    rotate.setDuration(时间) --设置毫秒1000=1秒
    rotate.setRepeatCount(10)
    view.startAnimation(rotate)
end

function 开关颜色(id, 颜色)
    id.ThumbDrawable.setColorFilter(PorterDuffColorFilter(颜色, PorterDuff.Mode.SRC_ATOP));
    id.TrackDrawable.setColorFilter(PorterDuffColorFilter(颜色, PorterDuff.Mode.SRC_ATOP))
end

function 拖动条颜色(id, 颜色)
    id.ProgressDrawable.setColorFilter(PorterDuffColorFilter(颜色, PorterDuff.Mode.SRC_ATOP))
    id.Thumb.setColorFilter(PorterDuffColorFilter(颜色, PorterDuff.Mode.SRC_ATOP))
end

function 小伍提示(str, a, b, c, d, e) --小伍自制提示
    if time then toasttime = Toast.LENGTH_SHORT else toasttime = Toast.LENGTH_SHORT end
    toasts = {
        LinearLayout,
        layout_height = "fill",
        layout_width = "fill",
        orientation = "vertical",
        {
            LinearLayout,
            layout_width = "match_parent",
            layout_height = "match_parent",
            orientation = "vertical",
            {
                LinearLayout,
                layout_width = "30dp",
                layout_height = "30dp",
                orientation = "horizontal",
                background = "chart/ts1.png",
                layout_gravity = "center",
                background = d,
            },
        },
        {
            CardView,
            id = "toastb",
            layout_width = "match_parent",
            layout_height = "match_parent",
            CardElevation = "1dp",
            radius = e,
            {
                LinearLayout,
                layout_width = "match_parent",
                layout_height = "match_parent",
                orientation = "horizontal",
                background = c,
                {
                    TextView,
                    id = "mess",
                    TextColor = a,
                    textSize = b,
                    layout_width = "match_parent",
                    layout_height = "match_parent",
                    gravity = "center",
                    layout_margin = "4dp",
                },
            },
        },
    };
    message = tostring(str)
    local toast = Toast.makeText(activity, "内容", toasttime);
    toast.setView(loadlayout(toasts))
    mess.Text = message
    toast.show()
end

function 隐藏控件(id)
    id.setVisibility(View.GONE)
end

function 显示控件(id)
    id.setVisibility(View.VISIBLE)
end

function 写入文件1(路径, 内容)
    import "java.io.File"
    f = File(tostring(File(tostring(路径)).getParentFile())).mkdirs()
    io.open(tostring(路径), "w"):write(tostring(内容)):close()
end

function 设置控件颜色(控件, 颜色)
    控件.setBackgroundColor(颜色)
end

import "android.media.MediaPlayer"
local mp = MediaPlayer()
function 播放(路径)
    mp.reset()
    mp.setDataSource(路径)
    mp.prepare()
    mp.setLooping(false)
    mp.start()
end

function 透明动画(对象, a, b, 时长)
    import "android.animation.ObjectAnimator"
    ObjectAnimator().ofFloat(对象, "alpha", { a, b }).setDuration(时长).start()
    ObjectAnimator().ofFloat(对象, "alpha", { a, b }).setDuration(时长).start()
end

function 波纹动画(控件, 颜色)
    import "android.widget.PageView"

    import "android.widget.RippleHelper"
    RippleHelper(控件).RippleColor = tonumber(颜色)
end

主页动画 = (PageView.PageTransformer {

    transformPage = function(page, position)
        local width = page.getWidth();

        local pivotX = 0;

        if (position <= 1 and position > 0) then
            local pivotX = 0
        elseif (position == 0) then

        elseif (position < 0 and position >= -1) then
            local pivotX = width
        end

        page.setPivotX(pivotX);

        page.setPivotY(activity.getHeight() / 2);

        page.setRotationY(90 * position);
    end

})

悬浮动画 = (PageView.PageTransformer {

    transformPage = function(page, position)
        width = page.getWidth();

        height = page.getHeight()

        pivotX = 0;

        if (position <= 1 and position > 0) then
            pivotX = 0

            pivotY = 0
        elseif (position == 0) then

        elseif (position < 0 and position >= -1) then
            pivotX = width

            pivotY = height
        end

        page.setPivotX(pivotX);

        page.setPivotY(pivotY / 2);

        page.setRotationY(90 * position);
    end

})


--进入子页面
--[[function 进入子页面(zym)
  activity.newActivity(zym)
end]]



function 发送邮件(邮箱, 标题, 内容)
    import "android.content.Intent"
    i = Intent(Intent.ACTION_SEND)
    i.setType("message/rfc822")
    i.putExtra(Intent.EXTRA_EMAIL, { 邮箱 })
    i.putExtra(Intent.EXTRA_SUBJECT, 标题)
    i.putExtra(Intent.EXTRA_TEXT, 内容)
    activity.startActivity(Intent.createChooser(i, "Choice"))
end

--调用方法
--发送邮件("782268899@qq.com","填写标题","填写要发送的内容")

function 查看QQ资料(账号)
    import "android.content.Intent"
    import "android.net.Uri"
    this.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("mqqapi://card/show_pslcard?uin=" .. 账号)))
end

--调用方法
--查看QQ资料(2975208179)




--执行Shell
function 执行Shell(cmd)
    local p = io.popen(string.format('%s', cmd))
    local s = p:read("*a")
    p:close()
    return s
end

--写入文件
function 写入文件(文件路径, 写入内容)
    io.open(文件路径, "w"):write(写入内容):close()
end

--打印
function 打印(内容)
    print(内容)
end

function md主题()
    activity.setTheme(android.R.style.Theme_DeviceDefault_Light) --设置md主题
end

function 顶栏颜色(color)
    if Build.VERSION.SDK_INT >= 21 then
        activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS).setStatusBarColor(
            color);
    end
end

function 跳转界面(main, text)
    activity.newActivity(main, { text })
end

function 关闭界面()
    activity.finish()
end

function 是否存在文件(path)
    if File(path).exists() then
        return true
    else
        return false
    end
end

function 追加写入文件(path, text)
    io.open(path, "w+"):write(text):close()
end

function 弹出消息(txt)
    Toast.makeText(activity, txt, Toast.LENGTH_SHORT).show()
end

function 控件可见(a)
    a.setVisibility(View.VISIBLE)
end

function 控件不可见(a)
    a.setVisibility(View.INVISIBLE)
end

function 控件隐藏(a)
    a.setVisibility(View.GONE)
end

function 解压缩(压缩路径, 解压缩路径)
    ZipUtil.unzip(压缩路径, 解压缩路径)
end

function 压缩(原路径, 压缩路径, 名称)
    LuaUtil.zip(原路径, 压缩路径, 名称)
end

function 删除文件1(路径)
    LuaUtil.rmDir(File(路径))
end

function 波纹(id, 颜色)
    import "android.content.res.ColorStateList"
    local attrsArray = { android.R.attr.selectableItemBackgroundBorderless }
    local typedArray = activity.obtainStyledAttributes(attrsArray)
    ripple = typedArray.getResourceId(0, 0)
    Pretend = activity.Resources.getDrawable(ripple)
    Pretend.setColor(ColorStateList(int[0].class { int {} }, int { 颜色 }))
    id.setBackground(Pretend.setColor(ColorStateList(int[0].class { int {} }, int { 颜色 })))
end

--文件操作--
function 写入文件3(路径, 内容)
    xpcall(function()
        f = File(tostring(File(tostring(路径)).getParentFile())).mkdirs()
        io.open(tostring(路径), "w"):write(tostring(内容)):close()
    end, function()
        提示("写入文件 " .. 路径 .. " 失败")
    end)
end

function 读取文件3(路径)
    if 文件是否存在(路径) then
        rtn = io.open(路径):read("*a")
    else
        rtn = ""
    end
    return rtn
end

function 复制文件3(from, to)
    xpcall(function()
        LuaUtil.copyDir(from, to)
    end, function()
        提示("复制文件 从 " .. from .. " 到 " .. to .. " 失败")
    end)
end

function 创建文件夹2(file)
    xpcall(function()
        File(file).mkdir()
    end, function()
        提示("创建文件夹 " .. file .. " 失败")
    end)
end

function 创建文件2(file)
    xpcall(function()
        File(file).createNewFile()
    end, function()
        提示("创建文件 " .. file .. " 失败")
    end)
end

function 创建多级文件夹2(file)
    xpcall(function()
        File(file).mkdirs()
    end, function()
        提示("创建文件夹 " .. file .. " 失败")
    end)
end

function 删除文件2(file)
    xpcall(function()
        LuaUtil.rmDir(File(file))
    end, function()
        提示("删除文件(夹) " .. file .. " 失败")
    end)
end

function 文件修改时间(path)
    f = File(path);
    time = f.lastModified()
    return time
end

function 内置存储路径(t)
    return Environment.getExternalStorageDirectory().toString() .. "/" .. t
end

function 追加写入文件(path, text)
    io.open(path, "w+"):write(text):close()
end

function 替换文件字符串(路径, 要替换的字符串, 替换成的字符串)
    if 路径 then
        路径 = tostring(路径)
        内容 = io.open(路径):read("*a")
        io.open(路径, "w+"):write(tostring(内容:gsub(要替换的字符串, 替换成的字符串))):close()
    else
        return false
    end
end

function 解压缩(压缩路径, 解压缩路径)
    xpcall(function()
        ZipUtil.unzip(压缩路径, 解压缩路径)
    end, function()
        提示("解压文件 " .. 压缩路径 .. " 失败")
    end)
end

function 压缩(原路径, 压缩路径, 名称)
    xpcall(function()
        LuaUtil.zip(原路径, 压缩路径, 名称)
    end, function()
        提示("压缩文件 " .. 原路径 .. " 至 " .. 压缩路径 .. "/" .. 名称 .. " 失败")
    end)
end

function 重命名文件(旧, 新)
    xpcall(function()
        File(旧).renameTo(File(新))
    end, function()
        提示("重命名文件 " .. 旧 .. " 失败")
    end)
end

function 移动文件2(旧, 新)
    xpcall(function()
        File(旧).renameTo(File(新))
    end, function()
        提示("移动文件 " .. 旧 .. " 至 " .. 新 .. " 失败")
    end)
end

--/文件操作--

--获取设备--
function 获取设备标识码()
    import "android.provider.Settings$Secure"
    return Secure.getString(activity.getContentResolver(), Secure.ANDROID_ID)
end

function 获取IMEI()
    import "android.content.Context"
    return activity.getSystemService(Context.TELEPHONY_SERVICE).getDeviceId()
end

function 获取状态栏高度()
    return activity.getResources().getDimensionPixelSize(luajava.bindClass("com.android.internal.R$dimen")()
        .status_bar_height)
end

function 获取设备型号()
    return Build.MODEL
end

function 获取ROM类型()
    return string.upper(Build.MANUFACTURER)
end

function 获取SDK版本()
    return tonumber(Build.VERSION.SDK)
end

function 获取安卓版本()
    return Build.VERSION.RELEASE
end

function 获取屏幕尺寸()
    import "android.util.DisplayMetrics"
    local dm = DisplayMetrics();
    activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
    diagonalPixels = Math.sqrt(Math.pow(dm.widthPixels, 2) + Math.pow(dm.heightPixels, 2));
    return diagonalPixels / (160 * dm.density);
end

function 获取手机内置存储剩余空间()
    fs = StatFs(Environment.getDataDirectory().getPath())
    return 格式化文件大小(fs.getAvailableBytes())
end

function 获取手机内置存储空间()
    path = Environment.getExternalStorageDirectory()
    stat = StatFs(path.getPath())
    blockSize = stat.getBlockSize()
    totalBlocks = stat.getBlockCount()
    return 格式化文件大小(blockSize * totalBlocks)
end

--/获取设备--

--一些函数--
function 格式化文件大小(fileSize)
    if (fileSize < 1024) then
        return fileSize + 'B';
    elseif (fileSize < (1024 * 1024)) then
        temp = fileSize / 1024;
        --temp = temp.toFixed(2);
        temp = 四舍五入(temp, 2)
        return temp .. 'KB';
    elseif (fileSize < (1024 * 1024 * 1024)) then
        temp = fileSize / (1024 * 1024);
        --temp = temp.toFixed(2);
        temp = 四舍五入(temp, 2)
        return temp .. 'MB';
    else
        temp = fileSize / (1024 * 1024 * 1024);
        --temp = temp.toFixed(2);
        temp = 四舍五入(temp, 2)
        return temp .. 'GB';
    end
end

function 四舍五入(num, n)
    local n = n - 1
    ws = "0"
    for i = 0, n do
        if ws == "0" then
            ws = "0."
        end
        ws = ws .. "0"
    end
    import "java.text.DecimalFormat"
    import "android.icu.text.DecimalFormat"
    formatter = DecimalFormat(ws);
    local s = formatter.format(num);
    ws = nil
    return s;
end

function 获取视频第一帧(path)
    import "android.media.MediaMetadataRetriever"
    media = MediaMetadataRetriever()
    media.setDataSource(tostring(path))
    return media.getFrameAtTime()
end

function 背景圆角(view, InsideColor, radiu)
    import "android.graphics.drawable.GradientDrawable"
    drawable = GradientDrawable()
    drawable.setShape(GradientDrawable.RECTANGLE)
    drawable.setColor(InsideColor)
    drawable.setCornerRadii({ radiu, radiu, radiu, radiu, radiu, radiu, radiu, radiu });
    view.setBackgroundDrawable(drawable)
end

function 匹配汉字(s)
    local ss = {}
    for k = 1, #s do
        local c = string.byte(s, k)
        if not c then break end
        if (c >= 48 and c <= 57) or (c >= 65 and c <= 90) or (c >= 97 and c <= 122) then
            if not string.char(c):find("%w") then
                table.insert(ss, string.char(c))
            end
        elseif c >= 228 and c <= 233 then
            local c1 = string.byte(s, k + 1)
            local c2 = string.byte(s, k + 2)
            if c1 and c2 then
                local a1, a2, a3, a4 = 128, 191, 128, 191
                if c == 228 then
                    a1 = 184
                elseif c == 233 then
                    a2, a4 = 190, c1 ~= 190 and 191 or 165
                end
                if c1 >= a1 and c1 <= a2 and c2 >= a3 and c2 <= a4 then
                    k = k + 2
                    table.insert(ss, string.char(c, c1, c2))
                end
            end
        end
    end
    return table.concat(ss)
end

function px2dp(pxValue)
    local scale = this.getResources().getDisplayMetrics().density
    return (pxValue / scale + 0.5)
end

function dp2px(dpValue)
    local scale = this.getResources().getDisplayMetrics().density
    return (dpValue * scale + 0.5)
end

function sp2px(spValue)
    local fontScale = this.getResources().getDisplayMetrics().scaledDensity
    return (spValue * fontScale + 0.5)
end

function 随机数(最小值, 最大值)
    return math.random(最小值, 最大值)
end

function 静态渐变(a, b, id, fx)
    if fx == "竖" then
        fx = GradientDrawable.Orientation.TOP_BOTTOM
    end
    if fx == "横" then
        fx = GradientDrawable.Orientation.LEFT_RIGHT
    end
    drawable = GradientDrawable(fx, {
        a, --右色
        b, --左色
    });
    id.setBackgroundDrawable(drawable)
end

function 对话框按钮颜色(dialog, button, WidgetColor)
    if button == 1 then
        dialog.getButton(dialog.BUTTON_POSITIVE).setTextColor(WidgetColor)
    elseif button == 2 then
        dialog.getButton(dialog.BUTTON_NEGATIVE).setTextColor(WidgetColor)
    elseif button == 3 then
        dialog.getButton(dialog.BUTTON_NEUTRAL).setTextColor(WidgetColor)
    end
end

function 关闭对话框(an)
    an.dismiss()
end

function 检测键盘状态()
    imm = activity.getSystemService(Context.INPUT_METHOD_SERVICE)
    isOpen = imm.isActive()
    return isOpen == true or false
end

function 隐藏键盘()
    activity.getSystemService(INPUT_METHOD_SERVICE).hideSoftInputFromWindow(
        WidgetSearchActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS)
end

function 显示键盘(id)
    activity.getSystemService(INPUT_METHOD_SERVICE).showSoftInput(id, 0)
end

function 复制文本(文本)
    activity.getSystemService(Context.CLIPBOARD_SERVICE).setText(文本)
end

function 全屏()
    activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
end

function 退出全屏()
    activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
end

function 图片高斯模糊(id, tp, radius1, radius2)
    function blur(context, bitmap, blurRadius)
        renderScript = RenderScript.create(context);
        blurScript = ScriptIntrinsicBlur.create(renderScript, Element.U8_4(renderScript));
        inAllocation = Allocation.createFromBitmap(renderScript, bitmap);
        outputBitmap = bitmap;
        outAllocation = Allocation.createTyped(renderScript, inAllocation.getType());
        blurScript.setRadius(blurRadius);
        blurScript.setInput(inAllocation);
        blurScript.forEach(outAllocation);
        outAllocation.copyTo(outputBitmap);
        inAllocation.destroy();
        outAllocation.destroy();
        renderScript.destroy();
        blurScript.destroy();
        return outputBitmap;
    end

    bitmap = loadbitmap(tp)
    function blurAndZoom(context, bitmap, blurRadius, scale)
        return zoomBitmap(blur(context, zoomBitmap(bitmap, 1 / scale), blurRadius), scale);
    end

    function zoomBitmap(bitmap, scale)
        w = bitmap.getWidth();
        h = bitmap.getHeight();
        matrix = Matrix();
        matrix.postScale(scale, scale);
        bitmap = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
        return bitmap;
    end

    加深后的图片 = blurAndZoom(activity, bitmap, radius1, radius2)
    id.setImageBitmap(加深后的图片)
end

function 获取应用信息(archiveFilePath)
    pm = activity.getPackageManager()
    info = pm.getPackageInfo(archiveFilePath, PackageManager.GET_ACTIVITIES);
    if info ~= nil then
        appInfo = info.applicationInfo;
        appName = tostring(pm.getApplicationLabel(appInfo))
        packageName = appInfo.packageName;     --安装包名称
        version = info.versionName;            --版本信息
        icon = pm.getApplicationIcon(appInfo); --图标
    end
    return packageName, version, icon
end

function 编辑框颜色(eid, color)
    eid.getBackground().setColorFilter(PorterDuffColorFilter(color, PorterDuff.Mode.SRC_ATOP))
end

function 获取文件MIME(name)
    ExtensionName = tostring(name):match("%.(.+)")
    Mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(ExtensionName)
    return tostring(Mime)
end

function xdc(url, path)
    require "import"
    import "java.net.URL"
    local ur = URL(url)
    import "java.io.File"
    file = File(path);
    local con = ur.openConnection();
    local co = con.getContentLength();
    local is = con.getInputStream();
    local bs = byte[1024]
    local len, read = 0, 0
    import "java.io.FileOutputStream"
    local wj = FileOutputStream(path);
    len = is.read(bs)
    while len ~= -1 do
        wj.write(bs, 0, len);
        read = read + len
        pcall(call, "ding", read, co)
        len = is.read(bs)
    end
    wj.close();
    is.close();
    pcall(call, "dstop", co)
end

function appDownload(url, path)
    thread(xdc, url, path)
end

function 申请权限(权限)
    ActivityCompat.requestPermissions(this, 权限, 1)
end

function 安装apk(安装包路径)
    import "android.content.Intent"
    import "android.net.Uri"
    intent = Intent(Intent.ACTION_VIEW)
    intent.setDataAndType(Uri.parse("file:///" .. 安装包路径), "application/vnd.android.package-archive")
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
    activity.startActivity(intent)
end

function 浏览器打开(pageurl)
    import "android.content.Intent"
    import "android.net.Uri"
    viewIntent = Intent("android.intent.action.VIEW", Uri.parse(pageurl))
    activity.startActivity(viewIntent)
end

function 设置图片(preview, url)
    preview.setImageBitmap(loadbitmap(url))
end

function 设置开关颜色(id, color, color2)
    id.ThumbDrawable.setColorFilter(PorterDuffColorFilter(转0x(color), PorterDuff.Mode.SRC_ATOP))
    id.TrackDrawable.setColorFilter(PorterDuffColorFilter(转0x(color2), PorterDuff.Mode.SRC_ATOP))
end

function 颜色字体(t, c)
    local sp = SpannableString(t)
    sp.setSpan(ForegroundColorSpan(转0x(c)), 0, #sp, Spannable.SPAN_EXCLUSIVE_INCLUSIVE)
    return sp
end

function 判断有无网络()
    local wl = activity.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE).getActiveNetworkInfo();
    if wl == nil then
        netl = false
    else
        netl = true
    end
    return netl
end

function 沉浸状态栏()
    --这个需要系统SDK19以上才能用
    if Build.VERSION.SDK_INT >= 19 then
        activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
    end
end

--/一些函数--

--用户界面--
function 跳转页面(ym, cs)
    if cs then
        activity.newActivity(ym, cs)
    else
        activity.newActivity(ym)
    end
end

function 渐变跳转页面(ym, cs)
    if cs then
        activity.newActivity(ym, android.R.anim.fade_in, android.R.anim.fade_out, cs)
    else
        activity.newActivity(ym, android.R.anim.fade_in, android.R.anim.fade_out)
    end
end

--/其他/--
import "android.content.Context"
function 获取剪贴板()
    return activity.getSystemService(Context.CLIPBOARD_SERVICE).getText()
end

function 写入剪贴板(text)
    activity.getSystemService(Context.CLIPBOARD_SERVICE).setText(text)
end

function 替换字符串(原字符串, 替换的字符串, 替换成的字符串)
    _ = string.gsub(原字符串, 替换的字符串, 替换成的字符串)
end

function 安装判断(a)
    if pcall(function() activity.getPackageManager().getPackageInfo(a, 0) end) then
        return true
    else
        return false
    end
end

function 状态栏颜色2(n)
    window = activity.getWindow()
    window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
    window.setStatusBarColor(n)
    if n == 0x3f000000 then
        if SDK版本 >= 23 then
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR)
            window.setStatusBarColor(0xffffffff)
        end
    end
end

function 写入文件2(路径, 内容)
    xpcall(function()
        f = File(tostring(File(tostring(路径)).getParentFile())).mkdirs()
        io.open(tostring(路径), "w"):write(tostring(内容)):close()
    end, function()
        提示("写入文件 " .. 路径 .. " 失败")
    end)
end

function 读取文件2(路径)
    if 文件是否存在(路径) then
        rtn = io.open(路径):read("*a")
    else
        rtn = ""
    end
    return rtn
end

import "android.webkit.CookieSyncManager"
import "android.webkit.CookieManager"

function 设置Cookie(context, url, content)
    CookieSyncManager.createInstance(context)
    local cookieManager = CookieManager.getInstance()
    cookieManager.setAcceptCookie(true)
    cookieManager.removeSessionCookie()
    cookieManager.removeAllCookie()
    cookieManager.setCookie(url, content)
    CookieSyncManager.getInstance().sync()
end

function 获取Cookie(url)
    local cookieManager = CookieManager.getInstance();
    return cookieManager.getCookie(url);
end

function 清除应用数据()
    os.execute("pm clear " .. activity.getPackageName())
end

function 悬浮按钮(ID, 父布局, 图片, 颜色, 边距, 事件)
    布局 = {
        RelativeLayout,
        layout_height = "match_parent",
        layout_width = "match_parent",
        {
            CardView,
            layout_alignParentBottom = "true",
            layout_width = "56dp",
            layout_height = "56dp",
            backgroundColor = 颜色,
            layout_alignParentRight = "true",
            layout_margin = 边距,
            CardElevation = "4dp",
            radius = "28dp",
            id = ID,
            {
                LinearLayout,
                layout_width = "74dp",
                layout_height = "74dp",
                style = "?android:attr/buttonBarButtonStyle",
                id = "button",
                layout_gravity = "center",
                onClick = 事件,
                {
                    ImageView,
                    layout_width = "25dp",
                    layout_height = "25dp",
                    src = 图片,
                    layout_gravity = "center",
                    colorFilter = "#ffffffff",
                },
            },
        },
    };
    父布局.addView(loadlayout(布局))
end

function 保存图片(name, bm)
    if bm then
        import "java.io.FileOutputStream"
        import "java.io.File"
        import "android.graphics.Bitmap"
        name = tostring(name)
        f = File(name)
        out = FileOutputStream(f)
        bm.compress(Bitmap.CompressFormat.PNG, 90, out)
        out.flush()
        out.close()
        return true
    else
        return false
    end
end

function activity背景颜色(color)
    import "android.graphics.drawable.ColorDrawable"
    _window = activity.getWindow();
    _window.setBackgroundDrawable(ColorDrawable(color));
    _wlp = _window.getAttributes();
    _wlp.gravity = Gravity.BOTTOM;
    _wlp.width = WindowManager.LayoutParams.MATCH_PARENT;
    _wlp.height = WindowManager.LayoutParams.MATCH_PARENT; --WRAP_CONTENT
    _window.setAttributes(_wlp);
end
 --获取软件包名--本身
GetPackageName = function()
    return activity.getPackageName()
end


function 自定义布局对话框(标题, 布局名) --布局对话框
    local dialog = AlertDialog.Builder(activity)
        .setTitle(标题)
        .setView(loadlayout(布局名))
    dialog.show()
end

function 获取当前系统时间() --获取当前的时间
    return os.date("%Y-%m-%d %H:%M:%S")
end

function 文件修改时间(path) --获取文件修改时间-路径
    f = File(path);
    time = f.lastModified()
    return time
end

function 控件边框(id, r, t, y) --控件的边框
    import "android.graphics.Color"
    InsideColor = Color.parseColor(t)
    import "android.graphics.drawable.GradientDrawable"
    drawable = GradientDrawable()
    drawable.setShape(GradientDrawable.RECTANGLE)
    --设置填充色
    drawable.setColor(InsideColor)
    --设置圆角 : 左上 右上 右下 左下
    drawable.setCornerRadii({ r, r, r, r, r, r, r, r });
    --设置边框 : 宽度 颜色
    drawable.setStroke(2, Color.parseColor(y))
    view.setBackgroundDrawable(drawable)

    --例:控件边框(bt,5,"#ffffffff","#42A5F5")--id，度数，内框透明，边框颜色
end

function 渐变(id, left_jb, right_jb)
    import "android.graphics.drawable.GradientDrawable"
    drawable = GradientDrawable(GradientDrawable.Orientation.TR_BL, {
        right_jb, --右色
        left_jb,  --左色
    });
    id.setBackgroundDrawable(drawable)
end

function 检测输入法()
    imm = activity.getSystemService(Context.INPUT_METHOD_SERVICE)
    isOpen = imm.isActive()
    return isOpen == true or false
end

function Base64加密(data) --编码
    import "android.util.Base64"
    import "java.lang.*"
    import "android.util.*"
    import "android.content.*"
    local Base64 = luajava.bindClass("android.util.Base64")
    return Base64.encodeToString(String(data).getBytes(), Base64.NO_WRAP);
end

function Base64解密(data) --解码
    local Base64 = luajava.bindClass("android.util.Base64")
    return String(Base64.decode(data, Base64.DEFAULT)).toString()
end

function 选择路径(提示, StartPath, callback)
    import "android.widget.ArrayAdapter"
    import "android.widget.LinearLayout"
    import "android.widget.TextView"
    import "java.io.File"
    import "android.widget.ListView"
    import "android.app.AlertDialog"
    --创建ListView作为文件列表
    lv = ListView(activity).setFastScrollEnabled(true)
    --创建路径标签
    cp = TextView(activity)
    lay = LinearLayout(activity).setOrientation(1).addView(cp).addView(lv)
    ChoiceFile_dialog = AlertDialog.Builder(activity) --创建对话框
        --弹窗圆角(ChoiceFile_dialog.getWindow(),0xffffffff)
        .setTitle(提示)
        .setPositiveButton("确定", {
            onClick = function()
                callback(tostring(cp.Text))
            end
        })
        .setNegativeButton("取消", nil)
        .setView(lay)
        .show()
    adp = ArrayAdapter(activity, android.R.layout.simple_list_item_1)
    lv.setAdapter(adp)
    function SetItem(path)
        path = tostring(path)
        adp.clear()              --清空适配器
        cp.Text = tostring(path) --设置当前路径
        if path ~= "/" then      --不是根目录则加上../
            adp.add("../")
        end
        ls = File(path).listFiles()
        if ls ~= nil then
            ls = luajava.astable(File(path).listFiles()) --全局文件列表变量
            table.sort(ls, function(a, b)
                return (a.isDirectory() ~= b.isDirectory() and a.isDirectory()) or
                    ((a.isDirectory() == b.isDirectory()) and a.Name < b.Name)
            end)
        else
            ls = {}
        end
        for index, c in ipairs(ls) do
            if c.isDirectory() then --如果是文件夹则
                adp.add(c.Name .. "/")
            end
        end
    end

    lv.onItemClick = function(l, v, p, s) --列表点击事件
        项目 = tostring(v.Text)
        if tostring(cp.Text) == "/" then
            路径 = ls[p + 1]
        else
            路径 = ls[p]
        end
        if 项目 == "../" then
            SetItem(File(cp.Text).getParentFile())
        elseif 路径.isDirectory() then
            SetItem(路径)
        elseif 路径.isFile() then
            callback(tostring(路径))
            ChoiceFile_dialog.hide()
        end
    end
    import "android.graphics.Color"
    ChoiceFile_dialog.getButton(ChoiceFile_dialog.BUTTON_POSITIVE).setTextColor(主题色)
    ChoiceFile_dialog.getButton(ChoiceFile_dialog.BUTTON_NEGATIVE).setTextColor(主题色)
    SetItem(StartPath)
end

function 控件转图片(view)
    import "android.graphics.Bitmap"
    local linearParams = view.getLayoutParams()
    local vw = linearParams.width
    local linearParams = view.getLayoutParams()
    local vh = linearParams.height
    view.setDrawingCacheEnabled(true)
    view.layout(0, 0, vw, vh)
    return Bitmap.createBitmap(view.getDrawingCache())
end

function 执行Shell2(code)
    os.execute(code)
end

function 点击元素(Class名, 索引)
    if 索引 then
        加载Js("var element=document.getElementsByClassName(" ..
            Class名 ..
            ")[" .. 索引 .. "] if(typeof(element.onclick)=='undefined'){element.click()}else{element.onclick()}")
    else
        加载Js("var element=document.getElementsByClassName(" ..
            Class名 .. ")[0] if(typeof(element.onclick)=='undefined'){element.click()}else{element.onclick()}")
    end
end

function 返回网页顶部()
    加载Js("scrollTo(0,0)")
end

return 中文函数库


--[[屏蔽退出按钮
function onKeyDown(code,event)
  if code==4 then
    intent=Intent();
    intent.setAction("android.intent.action.MAIN");
    intent.addCategory("android.intent.category.HOME");
    activity.startActivity(intent)
  end
end]]
